import { Module } from "vuex";
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusById,
} from "@/service/login/login";
import { ILoginState } from "@/store/login/type";
import { IRootState } from "@/store/type";
import { IAccount } from "@/service/login/type";
import router from "@/router";
import cache from "@/utils/cache";
import { mapMenusToRoutes } from "@/utils/map-menus";
const loginModule: Module<ILoginState, IRootState> = {
  state() {
    return {
      id: "",
      token: "",
      userInfo: {},
      userMenus: "",
    };
  },
  mutations: {
    changToken(state, token: string) {
      state.token = token;
    },
    changUserInfo(state, userInfo: any) {
      state.userInfo = userInfo;
    },
    changUserMenus(state, userMenus: any) {
      state.userMenus = userMenus;
      mapMenusToRoutes(userMenus);
      // userMenus =>routes

      // 将routes=>route.main.childen
    },
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccount) {
      // 1.实现登录逻辑
      const loginResult: any = await accountLoginRequest(payload);
      const { id, token } = loginResult;
      cache.setCache("token", token);
      commit("changToken", token);
      // 请求用户信息
      const userInfo: any = await requestUserInfoById(id);
      commit("changUserInfo", userInfo);
      cache.setCache("userInfo", userInfo); //保存用户信息
      //   请求用户菜单
      const userMenusResult: any = await requestUserMenusById(userInfo.id);
      commit("changUserMenus", userMenusResult);
      router.push("/main");
    },
  },
};
export default loginModule;
